﻿using System.Text.Json;

namespace OAuthClient.Server
{
    public class TokenManage
    {
        private readonly string _dbPath;

        public TokenManage(IWebHostEnvironment env)
        {
            _dbPath = Path.Combine(env.ContentRootPath, "database");
        }
        public Dictionary<string, TokenInfo> Record => File.Exists(_dbPath) ?
            JsonSerializer.Deserialize<Dictionary<string, TokenInfo>>(File.ReadAllText(_dbPath)) : new();

        public TokenInfo Get(string key)
        {
            return Record[key];
        }

        public void Save(string key, TokenInfo token)
        {
            var db = Record;
            if (db.ContainsKey(key))
            {
                db[key] = token;
            }
            else
            {
                db.Add(key, token);
            }
            File.WriteAllText(_dbPath, JsonSerializer.Serialize(db));
        }

        public record TokenInfo(string AccessToken, string RefreshToken, DateTime Expires);

    }
}
